#include <QVBoxLayout>

#include <QApplication>
#include <QHeaderView>
#include <QItemSelectionModel>

#include "computate_panel.h"
#include "../src/system.h"

ComputatePanel::ComputatePanel(QWidget* _parent) : QWidget(_parent){
	
	QVBoxLayout* panel = new QVBoxLayout();
	
	tableView = new QTableView;

	delegate = new DoubleSpinBoxDelegate(this);
	tableView->setItemDelegate(delegate);
	
	restartButton = new QPushButton(tr("Restart"));
	connect(restartButton, SIGNAL(clicked()), this, SLOT(restart()));

	panel->addWidget(tableView);
	panel->addWidget(restartButton);
// 	panel->addStretch();
	
	setLayout(panel);
}

ComputatePanel::~ComputatePanel(){
	delete tableView;
	delete delegate;
	delete model;
}

void ComputatePanel::valueChanged(QModelIndex _index){
	system->setMode((unsigned int)_index.row());
	system->initialPosition();
	if (_index.column() == 0) system->setAlpha(_index.data().toDouble());
	else system->setGamma(_index.data().toDouble());
}

void ComputatePanel::restart(){
	//system->initialPosition();
	
	for (unsigned int row = 0; row < system->getTotalModes(); ++row) {
		for (int column = 0; column < 2; ++column) {
			QModelIndex index = model->index(row, column, QModelIndex());
			model->setData(index, QVariant(0.0));
		}
	}
	
}

void ComputatePanel::setSystem(System* _system){
	system = _system;
	
	if (system != NULL){
		model = new QStandardItemModel(system->getTotalModes(), 2);
		model->setHeaderData(0, Qt::Horizontal, tr("Amplitude"));
		model->setHeaderData(1, Qt::Horizontal, tr("Phase"));
		
		tableView->setModel(model);
		tableView->resizeColumnsToContents();
		tableView->horizontalHeader()->setStretchLastSection(true);
		
		for (unsigned int row = 0; row < system->getTotalModes(); ++row) {
			for (int column = 0; column < 2; ++column) {
				QModelIndex index = model->index(row, column, QModelIndex());
				model->setData(index, QVariant(0.0));
			}
		}
		connect(model, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(valueChanged(QModelIndex)));
	}

}
